<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="单据编号" prop="code">
        <el-input
          v-model="queryParams.code"
          placeholder="请输入单据编号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="单据阶段" prop="docStage">
        <el-input
          v-model="queryParams.docStage"
          placeholder="请输入单据阶段"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="审批结果" prop="approvalResult">
        <el-input
          v-model="queryParams.approvalResult"
          placeholder="请输入审批结果"
          clearable
          @keyup.enter.native="handleQuery"
          readonly
        />
      </el-form-item>
      <el-form-item label="是否生效" prop="isEffect">
        <el-input
          v-model="queryParams.isEffect"
          placeholder="请输入是否生效"
          clearable
          @keyup.enter.native="handleQuery"
          readonly
        />
      </el-form-item>
      <el-form-item label="是否关闭" prop="isClose">
        <el-input
          v-model="queryParams.isClose"
          placeholder="请输入是否关闭"
          clearable
          @keyup.enter.native="handleQuery"
          readonly
        />
      </el-form-item>
      <el-form-item label="是否作废" prop="isCancel">
        <el-input
          v-model="queryParams.isCancel"
          placeholder="请输入是否作废"
          clearable
          @keyup.enter.native="handleQuery"
          readonly
        />
      </el-form-item>
      <el-form-item label="创建时间" prop="createDate">
        <el-date-picker clearable
                        v-model="queryParams.createDate"
                        type="date"
                        value-format="yyyy-MM-dd"
                        placeholder="创建时间"
                        readonly>
        </el-date-picker>
      </el-form-item>
      <el-form-item label="修改时间" prop="modifyDate">
        <el-date-picker clearable
                        v-model="queryParams.modifyDate"
                        type="date"
                        value-format="yyyy-MM-dd"
                        placeholder="修改时间"
                        readonly>
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['caigou:caigouxunjia:add']"
        >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['caigou:caigouxunjia:edit']"
        >修改
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['caigou:caigouxunjia:remove']"
        >删除
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['caigou:caigouxunjia:export']"
        >导出
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="caigouxunjiaList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"/>
<!--      <el-table-column label="主键id" align="center" prop="id"/>-->
      <el-table-column label="单据编号" align="center" prop="code" width="180" fixed/>
      <el-table-column label="源单编号" align="center" prop="sourceCode" width="180" fixed/>
      <el-table-column label="单据日期" align="center" prop="docDate" width="180"/>
      <el-table-column label="单据阶段" align="center" prop="docStage">
        <template slot-scope="scope">
          <span v-if="scope.row.docStage == 0">编制完</span>
          <span v-if="scope.row.docStage == 1">执行中</span>
          <span v-if="scope.row.docStage == 2">执行完</span>
        </template>
      </el-table-column>
      <el-table-column label="审批结果" align="center" prop="approvalResult"/>
      <el-table-column label="是否生效" align="center" prop="isEffect">
        <template slot-scope="scope">
          <span v-if="scope.row.isEffect == 0 || scope.row.isEffect == undefined || scope.row.isEffect == null">否</span>
          <span v-else>是</span>
        </template>
      </el-table-column>
      <el-table-column label="是否关闭" align="center" prop="isClose">
        <template slot-scope="scope">
          <span v-if="scope.row.isClose == 0 || scope.row.isClose == undefined || scope.row.isClose == null">否</span>
          <span v-else>是</span>
        </template>
      </el-table-column>
      <el-table-column label="是否作废" align="center" prop="isCancel">
        <template slot-scope="scope">
          <span v-if="scope.row.isCancel == 0 || scope.row.isCancel == undefined || scope.row.isCancel == null">否</span>
          <span v-else>是</span>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="createDate" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="修改人" align="center" prop="modifyBy"/>
      <el-table-column label="修改时间" align="center" prop="modifyDate" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.modifyDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="160" fixed="right">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['caigou:caigouxunjia:edit']"
          >修改
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['caigou:caigouxunjia:remove']"
          >删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改采购询价对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="1300px" append-to-body
               :close-on-click-modal="false"
               :close-on-press-escape="false">
      <el-form ref="form" :model="form" :rules="rules" :inline="true" label-width="80px">
        <el-form-item label="单据编号" prop="code">
          <el-input v-model="form.code" placeholder="请输入单据编号" readonly/>
        </el-form-item>
        <el-form-item label="单据日期" prop="code">
          <el-date-picker clearable
                          v-model="form.docDate"
                          type="date"
                          value-format="yyyy-MM-dd"
                          placeholder="单据日期"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="单据阶段" prop="docStage">
          <el-input v-model="form.docStage" placeholder="单据阶段" readonly/>
        </el-form-item>
        <template>
          <el-button v-if="isMore" type="text" @click="isMore = !isMore">收起</el-button>
          <el-button v-else type="text" @click="isMore = !isMore">更多</el-button>
        </template>

        <div v-show="isMore">
          <el-form-item label="审批结果" prop="approvalResult">
            <el-input v-model="form.approvalResult" placeholder="审批结果" readonly/>
          </el-form-item>
          <el-form-item label="是否生效" prop="isEffect">
            <el-input v-model="form.isEffect" placeholder="是否生效" readonly/>
          </el-form-item>
          <el-form-item label="是否关闭" prop="isClose">
            <el-input v-model="form.isClose" placeholder="是否关闭" readonly/>
          </el-form-item>
          <el-form-item label="是否作废" prop="isCancel">
            <el-input v-model="form.isCancel" placeholder="是否作废" readonly/>
          </el-form-item>
          <el-form-item label="创建时间" prop="createDate">
            <el-date-picker clearable
                            v-model="form.createDate"
                            type="date"
                            value-format="yyyy-MM-dd"
                            placeholder="请选择创建时间"
                            readonly>
            </el-date-picker>
          </el-form-item>
          <el-form-item label="修改时间" prop="modifyDate">
            <el-date-picker clearable
                            v-model="form.modifyDate"
                            type="date"
                            value-format="yyyy-MM-dd"
                            placeholder="请选择修改时间"
                            readonly>
            </el-date-picker>
          </el-form-item>
        </div>
      </el-form>
      <el-tabs v-model="activeName" type="card" @tab-click="handleClick">
        <el-tab-pane label="采购申请" name="t1">
          <el-button plain icon="el-icon-plus" @click="addSelectBuyReq">采购申请</el-button>
          <el-button plain icon="el-icon-minus" v-show="buyReqSelectListIds.length > 0" @click="remSelectBuyReq">移除
          </el-button>
          <BuyReqSelect :buyReqArr="buyReqList" @selectBuyReqMethod="changeHandleBuyReq" ref="buyReqRef"/>
          <el-table
            :data="buyReqList"
            style="width: 100%"
            @selection-change="handleSelectionChangeBuyReq"
          >
            <el-table-column
              type="selection"
              width="55"
              :selectable="checkSelectable">
            </el-table-column>
            <el-table-column
              prop="code"
              label="单据编号"
              width="180">
            </el-table-column>
            <el-table-column
              prop="reqUserName"
              label="需求人"
              width="180">
            </el-table-column>
            <el-table-column
              prop="reqUserDept"
              label="需求部门">
            </el-table-column>
          </el-table>
          <el-button plain icon="el-icon-arrow-right" @click="addBuyReqGoodsListFromAskGoodsList">添加</el-button>
          <el-table
            :data="buyReqGoodsList"
            style="width: 100%"
            @selection-change="handleSelectionChangeBuyReqGoodsList"
          >
<!--            <el-table-column-->
<!--              type="selection"-->
<!--              width="55"-->
<!--              :selectable="checkSelectable">-->
<!--            </el-table-column>-->
            <el-table-column
              prop="sourceCode"
              label="单据编号"
              width="180">
            </el-table-column>
            <el-table-column
              prop="proName"
              label="需求人"
              width="180">
            </el-table-column>
            <el-table-column
              prop="number"
              label="数量">
            </el-table-column>
            <el-table-column
              prop="unitName"
              label="单位">
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <el-tab-pane label="明细" name="t2">
          <GoodsSelect :goodsList="goodsArr" :idAndNumberArr="idAndNumberArr" :formOpr="formOpr"
                       @selectGoodsMethod="changeHandleGoods" ref="goodsSelectRef"/>
        </el-tab-pane>

      </el-tabs>

      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listCaigouxunjia,
  getCaigouxunjia,
  getCaigouxunjiaInfo,
  delCaigouxunjia,
  addCaigouxunjia,
  updateCaigouxunjia, addCaigouxunjiaPlus
} from "@/api/caigou/caigouxunjia";
import GoodsSelect from "@/views/caigou/caigouxunjia/GoodsSelectB.vue";
import BuyReqSelect from "@/views/caigou/caigouxunjia/BuyReqSelect.vue";
import {getBuyReqPlus, getGoodsListByBuyReqIds, getInfoListByIds} from "@/api/caigou/buyReq";

export default {
  name: "Caigouxunjia",
  components: {GoodsSelect, BuyReqSelect},
  data() {
    return {
      isMore: false,
      //被选中的采购申请商品数组
      selectBuyReqGoodsList: [],
      //采购申请的商品列表
      buyReqGoodsList: [],
      //采购申请
      buyReqList: [],
      //操作  1-添加 修改  2 查看
      formOpr: 1,
      // 采购申请的商品的id 数量 对应数组
      idAndNumberArr: [],
      // 询价商品数组
      goodsArr: [],

      activeName: 't1',
      // 遮罩层
      loading: true,
      // 选中数组
      buyReqSelectListIds: [],
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 采购询价表格数据
      caigouxunjiaList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        code: null,
        docStage: null,
        approvalResult: null,
        isEffect: null,
        isClose: null,
        isCancel: null,
        createDate: null,
        modifyBy: null,
        modifyDate: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        modifyBy: [
          {required: true, message: "修改人不能为空", trigger: "change"}
        ],
      }
    };
  },
  watch: {
    buyReqList: {
      handler(newVal, oldVal) {
        console.log(newVal)
        if (newVal.length > 0) {
          this.formOpr = 4
        } else {
          this.formOpr = 1
        }
      },
      deep: true
    }
  },
  created() {
    this.getList();
  },
  methods: {
    addBuyReqGoodsListFromAskGoodsList() {
      let idAndNumber = [];
      this.selectBuyReqGoodsList.forEach(item => {
        idAndNumber.push({id: item.id, number: item.number})
      })
      this.buyReqGoodsList.forEach(buyReqGoods => {
        this.selectBuyReqGoodsList.forEach(selectBuyReqGoods => {
          if (buyReqGoods.id == selectBuyReqGoods.id) {
            buyReqGoods.status = 2;
          }
        })
      })
      this.$refs.goodsSelectRef.parentComponent(this.selectBuyReqGoodsList, idAndNumber)
    },
    cancelAddBuyReqGoodsListFromAskGoodsList(cancelGoods) {
      console.log('cancelAddBuyReqGoodsListFromAskGoodsList', cancelGoods)
    },
    // 检查是否可以勾选
    checkSelectable(row) {
      return row.status !== 2 // 状态为 2 禁用复选框（返回值为 true 启用，false 禁用）
    },
    // 移除采购申请
    remSelectBuyReq() {
      console.log('remIds', this.buyReqSelectListIds)
      let newList = [];
      this.buyReqList.forEach(item => {
        let id = this.buyReqSelectListIds.find(id => id == item.id)
        if (!id) {
          newList.push(item);
        }
      })
      this.buyReqList = newList;
      this.changeHandleBuyReq(newList);
    },
    // 添加采购申请 触发 BuyReqSelect组件的弹窗
    addSelectBuyReq() {
      this.$refs.buyReqRef.addSelect();
    },
    // 采购申请组件的回调
    changeHandleBuyReq(BuyReqArr) {
      console.log('changeHandleBuyReq', BuyReqArr)
      BuyReqArr.forEach(item => {
        this.buyReqList.push(item)
      })
      let newList = [];
      let ids = [];
      this.buyReqList.forEach(item => {
        let id = newList.find((i) => i.id == item.id)
        if (!id) {
          item.status = 1;
          newList.push(item);
          ids.push(item.id);
        }

      })
      this.buyReqList = newList;

      getGoodsListByBuyReqIds(ids).then(res => {
        console.log(res.data)
        this.buyReqGoodsList = res.data;


        this.selectBuyReqGoodsList = res.data;
        this.addBuyReqGoodsListFromAskGoodsList();
      })


    },
    // 商品选中的回调
    changeHandleGoods(goodsArr) {
      console.log('changeHandleGoods goodsArr')
      console.log(goodsArr);
      this.goodsArr = goodsArr;
    },

    handleClick(tab, event) {
      console.log(tab.name)
      console.log(tab, event);
    },
    /** 查询采购询价列表 */
    getList() {
      this.loading = true;
      listCaigouxunjia(this.queryParams).then(response => {
        this.caigouxunjiaList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        code: null,
        docStage: null,
        approvalResult: null,
        isEffect: null,
        isClose: null,
        isCancel: null,
        createBy: null,
        createDate: null,
        modifyBy: null,
        modifyDate: null,
        isDel: null,
        docDate: null
      };
      this.resetForm("form");


      //被选中的采购申请商品数组
      this.selectBuyReqGoodsList = [];
      //采购申请的商品列表
      this.buyReqGoodsList = [],
        //采购申请
        this.buyReqList = [],

        // 采购申请的商品的id 数量 对应数组
        this.idAndNumberArr = [],
        // 询价商品数组
        this.goodsArr = [];
      // 选中数组
      this.buyReqSelectListIds = [];
      this.ids = [];

    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 采购申请多选框选中数据
    handleSelectionChangeBuyReq(selection) {
      console.log('handleSelectionChangeBuyReq', selection);
      this.buyReqSelectListIds = selection.map(item => item.id);

      this.goodsArr = selection
    },
    handleSelectionChangeBuyReqGoodsList(selection) {
      this.selectBuyReqGoodsList = selection;

    },
    // 询价列表多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加采购询价";
      this.form.code = 'CGXJ-' + Date.now();
      this.$refs.goodsSelectRef.reset();
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getCaigouxunjiaInfo(id).then(response => {
        this.form = response.data.buyAsk;
        console.log('getCaigouxunjiaInfo',response.data)
        this.open = true;
        this.title = "修改采购询价";
        this.$refs.goodsSelectRef.parentComponent(response.data.goodsList,response.data.idAndNumberList)

      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateCaigouxunjia(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            console.log('submits', this.goodsArr)
            addCaigouxunjiaPlus({
              "buyAsk": {...this.form,sourceCode:this.buyReqList[0].code},
              "idAndNumberList": this.goodsArr
            }).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除采购询价编号为"' + ids + '"的数据项？').then(function () {
        return delCaigouxunjia(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('caigou/caigouxunjia/export', {
        ...this.queryParams
      }, `caigouxunjia_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
